#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/14 0014 13:55
# @Author  : lh1993
# @email   : lhln0119@163.com
# @File    : aliyun.py
# @Software: PyCharm

from tools import get_config
from aliyun.log import LogClient, GetLogsRequest, LogException
from aliyun.log import ListLogstoresRequest


class AliyunSLS(object):
    """阿里云日志服务相关信息查询
    https://github.com/aliyun/aliyun-log-python-sdk/blob/master/README_CN.md
    """

    def __init__(self):
        self.apikey = get_config.apikey
        self.apisecret = get_config.apisecret
        self.region = get_config.vpc_sls_region
        self.project = get_config.project
        self.client = LogClient(accessKeyId=self.apikey, accessKey=self.apisecret, endpoint=self.region)

    def getListLogstores(self):
        """获取某个project下的日志库列表

        :return: list
        """
        try:
            request = ListLogstoresRequest(self.project)
            res = self.client.list_logstores(request)
            return res.get_logstores()
        except LogException as e:
            print(e)
            return []

    def getLogs(self, project, logstore, query, fromTime, toTime, line=100):
        """消费特定日志库，查询日志

        :param project: project名称
        :param logstore: 日志库名称
        :param query: 查询语句
        :param fromTime: 开始时间
        :param toTime: 结束时间
        :param line: 查询结果返回的行数，查询语句有限制时，这里不生效。
        :return:
        """
        try:
            logs = []
            request = GetLogsRequest(
                project=project,
                logstore=logstore,
                fromTime=fromTime,
                toTime=toTime,
                topic='',
                query=query,
                line=line,
                offset=0,
                reverse=False)
            res = self.client.get_logs(request)
            for item in res.get_logs():
                logs.append(item.get_contents())
            return logs
        except LogException as e:
            print(e)
            return []